#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "log.hpp"

using namespace std;

const string defaultpath = "./dict.txt";
const string sep = ": ";

class dict
{
private:
    unordered_map<string, string> data;
    string filepath;

    void Load()
    {
        ifstream fp(filepath);
        if(!fp.is_open())
        {
            Log(Fatal, "file open error: %s", filepath);
            return;
        }

        string line;
        while(getline(fp, line))
        {
            if(line.empty()) continue;

            int pos = line.find(sep);
            if(pos == string::npos) continue;

            string english, chinese;
            english = line.substr(0, pos); //apple: 苹果, 前闭后开
            chinese = line.substr(pos+sep.size());

            if(english.empty() || chinese.empty()) continue;

            data.insert(make_pair(english, chinese));
            Log(Debug, "load data: %s", line.c_str());
        }
    }

public:
    dict(string path = defaultpath): filepath(path)
    {
        Load();
    }

    string translate(string english)
    {
        auto it = data.find(english);
        if(it == data.end()) return "???";

        return it->second;
    }

    ~dict()
    {

    }

};